<template>
  <el-row style="min-width: 1500px">
    <el-col :span="24">
      <div class="wrap_plan">
        <div style="display: flex">
          <header class="wrap_plan_header">播放计划</header>
          <el-button type="primary" @click="router.go(-1)"
            >返回上一页</el-button>
        </div>
        <div class="wrap_plan_navbar x-flex x-row-between">
          <el-dropdown ref="dropdownEmpty" trigger="contextmenu">
            <el-button
              size="large"
              :style="{
                backgroundColor: color === '#409eff' ? color : '#86d6ff',
                color: color === '#409eff' ? '#fff' : '#fff',
              }"
              @click="downLine(tableData)"
              >下线</el-button
            >
            <template #dropdown>
              <div class="x-p-8">请选择节目</div>
            </template>
          </el-dropdown>
          <div class="x-flex">
            <el-date-picker
              v-model="pickerRef"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY/MM/DD/HH:mm:ss"
              size="large"
              @change="changPicker"
            />
            <el-input
              v-model="inputSearch"
              class="x-m-l-10"
              size="large"
              placeholder="请输入名称或创建用户"
              :suffix-icon="Search"
              @change="inputSearchClick()"
            />
          </div>
        </div>
        <div class="wrap_plan_main">
          <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%"
            height="calc(90vh - 210px)"
            :header-cell-style="{ background: '#F6F7F9' }"
            @selection-change="multipleSelection = $event"
            @select-all="selectClick"
            @select="selectClick"
          >
            <template #empty>
              <div class="no-data">
                <el-empty
                  :image="require('../../assets/nothave.png')"
                  style="margin-top: 30%"
                >
                </el-empty>
              </div>
            </template>
            <el-table-column type="selection" width="55" />
            <el-table-column label="名称" show-overflow-tooltip>
              <template #default="{ row, data }">
                <div class="x-flex">
                  <img
                    style="width: 28px; height: 28"
                    src="../../assets/favicon.svg"
                    alt=""
                  />
                  <text class="x-m-l-8">{{ row.programName }}</text>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="时长" width="280">
              <template #default="{ row }">
                <div>{{ row.programTime }}s</div>
              </template>
            </el-table-column>
            <el-table-column label="播放计划" width="550">
              <template #default="{ row, data }">
                <div>
                  <el-icon color="#adb2b7"><Calendar /></el-icon
                  ><text class="x-m-l-8" style="vertical-align: 1px"
                    >{{ row.startDate }}-<span>{{ row.endDate }}</span></text
                  >
                </div>
                <div>
                  <div>
                    <el-icon color="#adb2b7"><AlarmClock /></el-icon
                    ><text class="x-m-l-8" style="vertical-align: 1px"
                      >{{ row.timeSlot }}
                    </text>
                  </div>
                </div>
                <div>
                  <el-icon color="#adb2b7"><RefreshRight /></el-icon
                  ><text class="x-m-l-8" style="vertical-align: 1px">{{
                    row.selectWeek
                  }}</text>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                  v-if="row.status == 0"
                  type="primary"
                  text
                  @click="downLines(row.id)"
                  >下线</el-button
                >
                <el-button v-if="row.status == 1" type="info" disabled text
                  >下线</el-button
                >
                <el-button v-if="row.status == 2" type="info" disabled text
                  >已过时效</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="--pages">
            <el-pagination
              v-model:current-page="currentPages"
              :page-sizes="[10, 20, 30, 40]"
              :total="total"
              background
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import { onMounted, ref, shallowRef, unref } from "vue";
import { ElMessage, ElTable, ElMessageBox } from "element-plus";
import {
  Search,
  Calendar,
  AlarmClock,
  RefreshRight,
} from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { delectDevice, programPage } from "@/api/advertising/index";
const route = useRoute();
const router = useRouter();
const dropdownEmpty = ref<any>("");
const pickerRef = ref("");
const inputSearch = ref("");
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref([]);
const color = ref("info");
//分页
const currentPages = shallowRef(1);
const pageSizes = shallowRef(10);
const total = shallowRef(90);
const deviceId = ref<any>("");
const tableData = ref([
  {
    picture: "http://dummyimage.com/492x122.png/34137b/0f2d05",
    name: "s_20239490084_0234",
    mode: "15s",
    date: "2023/04/09-2023/05/23",
    time: "01:00-03:00、04:00-12:00",
    week: "周一、周二、周三",
  },
]);
const startDate = ref("");
const endDate = ref("");
const startDates = ref("");
const endDates = ref("");
// 分页
const programPageasync = async () => {
  let data = {
    pageNum: currentPages.value,
    pageSize: pageSizes.value,
    programId: "",
    startDate: startDates.value,
    deviceId: deviceId.value,
    endDate: endDates.value,
    deviceName: "",
    programName: inputSearch.value,
  };
  let result = await programPage(data);
  if (result.data.data) {
    result.data.data.content.forEach((item: any) => {
      startDate.value = item.startDate.split(" ")[1];
      endDate.value = item.endDate.split(" ")[1];
    });
    function convertSelectWeek(selectWeek: any) {
      const weekdays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
      const weekNumbers = selectWeek.split(",").map(Number);
      const selectedWeekdays = weekNumbers.map(
        (weekNumber: any) => weekdays[weekNumber - 1]
      );
      return selectedWeekdays.join("  、  ");
    }
    result.data.data.content.forEach((item: any) => {
      item.selectWeek = convertSelectWeek(item.selectWeek);
    });
    result.data.data.content.map((item) => {
      const endDate = new Date(item.endDate);
      item.endDate = endDate.toLocaleDateString(); // 获取格式化后的日期字符串
      const startDate = new Date(item.startDate);
      item.startDate = startDate.toLocaleDateString(); // 获取格式化后的日期字符串
      item.timeSlot = item.timeSlot.replace(/,/g, " 、");
    });
    tableData.value = result.data.data.content;

    total.value = result.data.data.totalElements;
  }
};
// 下线
const downLine = async (rows: any) => {
  if (rows) {
    let selectGrouping = unref(multipleTableRef)!.getSelectionRows();
    if (selectGrouping.length > 1) {
      ElMessage({
        message: "只能选择一个节目进行审核",
        type: "warning",
        duration: 1000,
      });
      return;
    }
    if (selectGrouping.length > 0) {
      let id = multipleSelection.value.map((item: any) => item.id);
      let res = await delectDevice(id);
      if (res.data.code == 1) {
        programPageasync();
        ElMessage({
          message: res.data.msg,
          type: "success",
          duration: 1000,
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: "error",
          duration: 1000,
        });
      }
    } else {
      if (!unref(dropdownEmpty)) return;
      unref(dropdownEmpty).handleOpen();
    }
  }
};
// 选中
const selectClick = (val) => {
  if (val.length > 0) {
    color.value = "#409eff";
  } else {
    color.value = "#f0f2f5";
  }
};
// 右侧下线
const downLines = async (id: any) => {
  ElMessageBox.confirm("确定下线吗?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await delectDevice(id);
      if (res.data.code == 1) {
        programPageasync();
        ElMessage({
          message: res.data.msg,
          type: "success",
          duration: 1000,
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: "error",
          duration: 1000,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消下线",
      });
    });
};
// 搜索
const inputSearchClick = () => {
  programPageasync();
};
// 选中时间
const changPicker = (val: any) => {
  if (val) {
    startDates.value = val[1].replace("00:00:00", "00:00:00");
    endDates.value = val[0].replace("00:00:00", "23:59:59");

    programPageasync();
  } else {
    startDates.value = "";
    endDates.value = "";
    programPageasync();
  }
};
const handleSizeChange = (val: number) => {
  pageSizes.value = val;
  programPageasync();
};
const handleCurrentChange = (val: number) => {
  currentPages.value = val;
  programPageasync();
};
onMounted(() => {
  deviceId.value = route.query.id
    ? route.query.id
    : localStorage.getItem("goID");
  programPageasync();
});
</script>
<style scoped>
::v-deep .el-input input::selection {
  background-color: #79bbff;
}
.wrap_plan {
  width: 100%;
  height: calc(100vh - 100px);
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
  .wrap_plan_header {
    width: 100%;
    height: 40px;
    line-height: 30px;
    font-weight: 500;
    font-size: 14px;
    border-bottom: 1px solid #ebeff3;
  }
  .wrap_plan_navbar {
    padding: 16px 0;
  }
  .wrap_plan_main {
    .--pages {
      width: 100%;
      height: 72px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
